# 2024/4/17 下午3:09 HFL
import requests

from utils.log import LoggerUtils


class Request(object):
    # 使用单例模式来共享一个Session对象和日志对象，以提高性能和减少资源消耗
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super(Request, cls).__new__(cls)
            cls._instance.__init__()
        return cls._instance

    def __init__(self):
        self.session = requests.Session()
        self.log = LoggerUtils().logger()

    def _handle_exception(self, e, url, method):
        # 细化异常处理
        error_massage = f'请求异常：{e}'
        if isinstance(e, requests.exceptions.Timeout):
            error_massage = f'请求：{method} {url}超时'
        elif isinstance(e, requests.exceptions.HTTPError):
            error_massage = f'请求：{method} {url} 返回HTTP错误 ：{e.response.status_code}'
        elif isinstance(e, requests.exceptions.ConnectionError):
            error_massage = f'请求：{method} {url},发生连接错误:{e}'
        self.log.error(error_massage)

    def post(self, url, data=None, json=None, **kwargs):
        method = "POST"
        try:
            # self._log_request_details(method=method, url=url, data=data, json=json)
            res = self.session.post(url=url, data=data, json=json, **kwargs)
            self.log.info(f'=========>请求成功,响应状态码:{res.status_code}')
            self.log.info(f'=========>请求方法：{method}')
            self.log.info(f'=========>请求URL：{url}')
            self.log.info(f'=========>请求响应时间:{res.elapsed.total_seconds()}')
            self.log.info(f'=========>JSON请求体：{json}')
            self.log.info(f'=========>Data请求体：{data}')
            self.log.info(f'响应码==>:{res.status_code}')
            self.log.info(f'接口响应体==>:{res.text}')
            return res
        except Exception as e:
            self._handle_exception(e, method=method, url=url)
            raise Exception(f'请求错误：{e}')

    def get(self, url, params=None, json=None, data=None,headers=None, **kwargs):
        method = 'GET'
        try:
            res = self.session.get(url=url, params=params, headers=headers,json=None, data=None, **kwargs)
            self.log.info(f'请求成功,响应状态码:{res.status_code}')
            self.log.info(f'=========>请求方法：{method}')
            self.log.info(f'=========>请求URL：{url}')
            self.log.info(f'=========>请求响应时间:{res.elapsed.total_seconds()}')
            self.log.info(f'=========>Params请求体：{params}')
            self.log.info(f'=========>JSON请求体：{json}')
            self.log.info(f'=========>Data请求体：{data}')
            self.log.info(f'接口响应体==>:{res.json()}')
            return res
        except Exception as e:
            self._handle_exception(e=e, method=method, url=url)
            raise Exception(f'请求错误：{e}')

    def put(self, url, data=None, **kwargs):
        method = 'PUT'
        try:
            res = self.session.put(url=url, data=data, **kwargs)
            self.log.info(f'请求成功,响应状态码:{res.status_code}')
            self.log.info(f'=========>请求方法：{method}')
            self.log.info(f'=========>请求URL：{url}')
            self.log.info(f'=========>请求响应时间:{res.elapsed.total_seconds()}')
            self.log.info(f'=========>Data请求体：{data}')
            self.log.info(f'接口响应体==>:{res.text}')
            return res
        except Exception as e:
            self._handle_exception(e=e, method=method, url=url)
            raise Exception(f'请求错误：{e}')


    def delete(self, url, **kwargs):
        method = 'DELETE'
        try:
            res = self.session.delete(url=url, **kwargs)
            self.log.info(f'请求成功,响应状态码:{res.status_code}')
            self.log.info(f'=========>请求方法：{method}')
            self.log.info(f'=========>请求URL：{url}')
            self.log.info(f'=========>请求响应时间:{res.elapsed.total_seconds()}')
            self.log.info(f'接口响应体==>:{res.text}')
            return res
        except Exception as e:
            self._handle_exception(e=e, method=method, url=url)
            raise Exception(f'请求错误：{e}')



